//
//  SDKManager.m
//  HollySdk
//
//  Created by hollycrm on 2021/3/4.
//

#import "SDKManager.h"
#import "RTCController.h"
#import "Request.h"

#define visitorId @"hunter"
//-(void)initRTCViewWithAppId:(UInt32)appId userSign:(NSString *)usig roomId:(UInt32)roomId userId:(NSString *)userId isInvite:(BOOL)isInvite toUserId:(NSString *)toUserId;

@interface SDKManager(){
    RTCController *rtccontroller;
}

@end

@implementation SDKManager
+ (instancetype)shareManager{
    static SDKManager * manager = nil;
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        manager = [[super allocWithZone:NULL] init];
    });
    return manager;
}

+ (id)allocWithZone:(struct _NSZone *)zone{
    return [self shareManager];
}

-(NSString *)getA6UserId:(NSString *)vid{
    return [NSString stringWithFormat:@"%@_visitor_%@",_account,vid];
}

-(void)initWithParam:(NSDictionary *)param succ:(void (^)(void))success fail:(void (^)(NSString * _Nonnull))failed{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:param];
    [params setObject:@"getRoomInfo" forKey:@"Action"];
    [params setObject:@"MeetRoom" forKey:@"Modual"];
    [params setObject:visitorId forKey:@"VisitorId"];
    self.account = [param valueForKey:@"Account"];
    Request *req = [Request new];
    [req post:params withUrl:requestUrl succ:^(NSDictionary * _Nonnull dic) {
        //NSLog([NSString stringWithFormat:@"**********%@",[dic description]]);
        [self initRTCViewWithAppId:[[dic valueForKey:@"SdkAppId"] intValue] userSign:[dic objectForKey:@"VisitorSig"] roomId:[[dic valueForKey:@"VideoRoomId"] intValue] userId:[self getA6UserId:[dic objectForKey:@"VisitorId"]] isInvite:true toUserId:[dic objectForKey:@"VisitorId"]];
        success();
    } fail:^(NSString * _Nonnull msg) {
        NSLog(@"%@", msg);
        failed(msg);
    }];
}

-(void)initRTCViewWithAppId:(UInt32)appId userSign:(NSString *)usig roomId:(UInt32)roomId userId:(NSString *)userId isInvite:(BOOL)isInvite toUserId:(NSString *)toUserId{
    RTCController *controller = [RTCController shareController];
    
    if (controller.inRoom && roomId == controller.roomId && [usig isEqualToString:controller.userSig] && appId == controller.sdkAppId && [userId isEqualToString:controller.userId] ) {
        //restore?
    }
    
    else if (isInvite) {
        controller.rtcCallState = invite;
        controller.sdkAppId = appId;
        controller.userSig = usig;
        controller.roomId = roomId;
        controller.touserid = toUserId;
        controller.userId = userId;
        [controller pushView];
    }
    else{
        controller.rtcCallState = call;
        controller.sdkAppId = appId;
        controller.userSig = usig;
        controller.roomId = roomId;
        controller.touserid = toUserId;
        controller.userId = userId;
        [controller enterRoomWithView:true];
    }
    
    
    
    
}
@end
